<?php

namespace App\Http\Controllers\Platform\Content;

use App\Application\Channel\Models\Channel;
use App\Application\Content\Client;
use App\Application\Content\Models\Content;
use Composer\Exceptions\ApiErrorCode;
use Composer\Exceptions\ApiException;
use Illuminate\Support\Facades\Auth;
use Spatie\QueryBuilder\AllowedFilter;

class ContentController extends Client
{

    public function __construct(Content $model)
    {
        parent::__construct($model);
        $this->allowedSorts = ['-comment_num', '-id'];
        $this->allowedFilters = [
            'title',
            AllowedFilter::exact('channel_id'),
            AllowedFilter::callback('is_my', function ($query, $value) {
                // 1 查询我发布的
                $where = [];
                if ($value == 1) {
                    $user = Auth::guard("platform")->user();
                    $where = [['user_id', '=', $user->id]];
                    // 2 所有人的列表
                }
                $query->where($where);
            }),
        ];
    }

    public function performCreate()
    {
        parent::performCreate();
        // $user = auth()->user("platform");
        $user = Auth::guard("platform")->user();
        $channelId = $this->data['channel_id'];
        $Channel = Channel::where("id", $channelId)->exists();
        if (!$Channel) {
            throw new ApiException('频道id不存在', ApiErrorCode::VALIDATION_ERROR);
        }
        $this->data['user_id'] = $user->id;
        $this->data['give_num'] = 0;
        $this->data['comment_num'] = 0;
    }

    public function afterCreate()
    {
        $channelId = $this->data['channel_id'];
        if ($this->row) {
            Channel::where("id", $channelId)->increment("content_num");
        }
    }
    public function performDelete()
    {
        $id = $this->id;
        $user = Auth::guard("platform")->user();
        $where = [
            "user_id" => $user->id,
            "id" => $id
        ];
        $isContent = $this->model->where($where)->exists();
        if (!$isContent) {
            throw new ApiException('你没权限删除', ApiErrorCode::VALIDATION_ERROR);
        }
    }
    public function performUpdate()
    {

        $this->validateRules = [
            'title' => 'required',
        ];
        $this->validateMessage = [
            'title.required' => '内容标题必须填写',
        ];
        parent::performUpdate();
        $user = Auth::guard("platform")->user();
        $this->model = $this->model->where("user_id", $user->id)->findOrFail($this->id);
    }
}
